﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Sendmail.Tests
{
    public class TestClient
    {
        private TcpClient _client;
        private readonly string _toAccount;
        private readonly string _msg;
        private readonly string _ip;
        private readonly int _port;

        public TestClient(string ip, int port, string toAccount, string msg)
        {
            _toAccount = toAccount;
            _msg = msg;
            _ip = ip;
            _port = port;
        }

        public void Run(object state)
        {
            _client = new TcpClient();
            _client.Connect(new IPEndPoint(IPAddress.Parse(_ip), _port));
            Write("EHLO");
            var strMessage = Read();
            if (strMessage.StartsWith("250 OK"))
            {
                Write(String.Format("RCPT TO: <{0}@gmail.com>", _toAccount));
                strMessage = Read();
            }
            if (strMessage.StartsWith("250 OK"))
            {
                Write("MAIL FROM: <nadawca@gmail.com>");
                strMessage = Read();
            }
            if (strMessage.StartsWith("250 OK"))
            {
                Write("DATA");
                Read();
                Write("Subject: Example Message\n");
                Write("From: Nadawca <nadawca@gmail.com>");
                Write(String.Format("To: Odbiorca  <{0}@gmail.com>", _toAccount));
                Write(_msg);
                Write("\r\n.\r\n");
                Read();
            }
            Write("QUIT");
            Read();
        }

        private void Write(String strMessage)
        {
            var clientStream = _client.GetStream();
            var encoder = new ASCIIEncoding();
            var buffer = encoder.GetBytes(strMessage);
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
        }

        private String Read()
        {
            var messageBytes = new byte[8192];
            var clientStream = _client.GetStream();
            var encoder = new ASCIIEncoding();
            var bytesRead = clientStream.Read(messageBytes, 0, 8192);
            return encoder.GetString(messageBytes, 0, bytesRead);
        }
    }
}